from fastapi import FastAPI, File, UploadFile, APIRouter
from fastapi.responses import JSONResponse
import os
from datetime import datetime

router = APIRouter()

# 定义图片保存的基础目录
UPLOAD_DIR = "/root/workspace/000054/SDxeon/backend/uploads"

@router.post("/v1/dataprep/image")
async def upload_image(image: UploadFile = File(...)):
    """
    处理图片上传的 API 端点
    1. 创建上传目录（如果不存在）
    2. 生成唯一的文件名
    3. 保存图片到指定目录
    """
    try:
        # 确保上传目录存在
        os.makedirs(UPLOAD_DIR, exist_ok=True)
        
        # 生成唯一的文件名（使用时间戳和原始文件名）
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        file_name = f"{timestamp}_{image.filename}"
        file_path = os.path.join(UPLOAD_DIR, file_name)
        
        # 保存上传的文件
        with open(file_path, "wb") as buffer:
            buffer.write(await image.read())
        
        return JSONResponse(content={
            "status": "success", 
            "file_path": file_path,
            "file_name": file_name
        }, status_code=200)
    
    except Exception as e:
        return JSONResponse(content={
            "status": "error", 
            "message": str(e)
        }, status_code=500) 